import Store from '@/utils/store';
import { history } from 'umi';
import { removeToken } from '@/utils/auth';
import { stringify } from 'querystring';

export default {
  namespace: 'user',
  state: {
    userInfo: {
      store_name: Store.fetchLocal('loginInfoSMP')
        ? Store.fetchLocal('loginInfoSMP').store_name
        : '',
      headimgurl: Store.fetchLocal('loginInfoSMP')
        ? Store.fetchLocal('loginInfoSMP').headimgurl
        : '',
    },
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
  effects: {
    // 更新用户信息
    *updateUserInfo({ payload }, { put }) {
      yield put({
        type: 'save',
        payload: { userInfo: payload },
      });
    },
    // 登出
    *logOut() {
      const queryString = stringify({
        redirect: window.location.href,
      });
      yield removeToken();
      history.push(`/user/login?${queryString}`);
    },
  },
};
